import React from "react";
import { Select, Modal, Icon, Form, Col,Checkbox, Row, Input,Button} from 'antd/lib';
import notification from "@/services/notification";
import {get} from "lodash";
import Uploads from "@/services/uploads";
import Upload from "antd/lib/upload";
import 'antd/dist/antd.less'
import moment from "moment";
import DatePicker from "antd/lib/date-picker";
import locale from 'antd/es/date-picker/locale/zh_CN';
import { currentUser } from "@/services/auth";
import Attaches from "@/services/attaches";
import {DeleteOutlined, UploadOutlined} from '@ant-design/icons';
import Customer from "@/services/customer";
const { confirm } = Modal;

export default class NoticeTable extends React.Component {
  state = {
    loading: true,
    id: 0,//
    
    orgunitid:currentUser.orgunit_id,
    departmentdata:[],
    annex:[],//--操作员ID
    annexorgunit:[],
    annexorgunitid:0,
    is_public:currentUser.isAdmin,
  };
  // componentDidMount() {
  //   const userId = this.props.userId || currentUser.id;
  // }
  componentWillMount() {
    this.refreshData(this.props.data);
    let params={
      code: "",
      name: "",
      userid: currentUser.id,
    }
    Customer.querydepartment(params).then(data => {
      this.setState({
        departmentdata: data,
      });
      let params = {
        sourceid: currentUser.orgunit_id,
        type: "orgunit",
      }
      Attaches.get(params).then(data => {
        if (data.id > 0) {
          this.setState({
            annexorgunit:data.annex,
            annexorgunitid:data.id,
            loading: false,
          });
        } else {
          this.setState({
            loading: false,
            annexorgunitid:0,
            annexorgunit:[],
          });
        }
      }).catch(error => {
          this.setState({
            loading: false,
            annexorgunitid:0,
            annexorgunit:[],
          });
        });
    });
    
  }
  componentDidMount() {
    　　this.props.onRef(this);
  }
     // 这种方式十分适合父子组件的互动，通常是父组件需要通过某些状态控制子组件渲染亦或销毁...
componentWillReceiveProps(nextProps) {//componentWillReceiveProps方法中第一个参数代表即将传入的新的Props
    this.refreshData(nextProps.data);
}
  refreshData(data) {
          this.setState({
            id: data.id,//
            annex: data.annex,//--操作员ID
            annexorgunit:data.annexorgunit,
            loading: false,
          });
  };
   handledown(file){
     let  filename=file.url;
     let names=file.name;
     if(names.split('.')[1]!==filename.split('.')[1]){
      filename=filename.split('.')[0] +'.'+names.split('.')[1];
     }
     let AjaxUrl = 'api/upload/downloadfile';
     fetch(AjaxUrl ,{
      method: 'POST',
      body: window.JSON.stringify({filename: filename}),
      credentials: 'include',
      headers: new Headers({
        'Content-Type': 'application/json'
      })}).then((response) => {
      response.blob().then(blob => {
        const aLink = document.createElement('a');
        document.body.appendChild(aLink);
        aLink.style.display='none';
        const objectUrl = window.URL.createObjectURL(blob);
        aLink.href = objectUrl;
        aLink.download = file.name;
        aLink.click();
        document.body.removeChild(aLink);
      });
    }).catch((error) => {
      console.log(error);
    });
  };
  getPdfURL(){
    const _this = this;
    const props = {
        name: 'file',
        action: 'api/upload/uploadfile/notice/editor/0/0/'+_this.props.id,
        headers: {
            authorization: 'authorization-text',
        },
     //  onChange: this.handleChange,
     onChange(info) {
            let fileList = [...info.fileList];

            // 1. Limit the number of uploaded files
            // Only to show two recent uploaded files, and old ones will be replaced by the new
            // fileList = fileList.slice(-2);
            // 2. Read from response and show file link
       var newd=[];
        fileList.forEach(file => {
              if (file.response) {
                // Component will show file.url as link
                file.url = 'static/file/'+file.response.filename;
              }
              let status = _this.state.status;
              if(file.bytstatus>=0){
                status=file.bytstatus;
              }
         // if(file.status==="done") {
             const b=[{
                      uid: file.uid,
                      name: file.name,
                      status: file.status,
                      bytstatus: status,
                      url: file.url
              }];
            if (newd.length < 1) {
              newd = b;
            } else {
              newd.push.apply(newd, b);
            }
         // }
            });
            _this.setState({ annex:newd });
          },
       onDownload: this.handledown,
       onRemove(infos){
        let uid=infos.uid;
        const id=_this.props.id;
        Uploads.removefile({sourcetype: "notice",sourceid:id,uid:uid}).then(data => {
             if(data.code==="sucess"){
                notification.success(data.msg);
             }
             else{
              notification.error(data.msg);
              }
            }).catch(error => {
              notification.error(get(error, "response.data.message", "删除失败."));
            });
       },
        showUploadList: {
        showDownloadIcon: true,
        downloadIcon: '下载',
        showRemoveIcon: true,
        removeIcon: <DeleteOutlined onClick={e => console.log(e, 'custom removeIcon event')} />,
      },
    };
    return props;
};
getPdfURLorgunit(){
  const _this = this;
  const props = {
      name: 'file',
      action: 'api/upload/uploadfile/noticeorgunit/editor/0/0/'+_this.props.id,
      headers: {
          authorization: 'authorization-text',
      },
   //  onChange: this.handleChange,
   onChange(info) {
          let fileList = [...info.fileList];

          // 1. Limit the number of uploaded files
          // Only to show two recent uploaded files, and old ones will be replaced by the new
          // fileList = fileList.slice(-2);
          // 2. Read from response and show file link
     var newd=[];
      fileList.forEach(file => {
            if (file.response) {
              // Component will show file.url as link
              file.url = 'static/file/'+file.response.filename;
            }
            let status = _this.state.status;
            if(file.bytstatus>=0){
              status=file.bytstatus;
            }
       // if(file.status==="done") {
           const b=[{
                    uid: file.uid,
                    name: file.name,
                    status: file.status,
                    bytstatus: status,
                    url: file.url
            }];
          if (newd.length < 1) {
            newd = b;
          } else {
            newd.push.apply(newd, b);
          }
       // }
          });
          _this.setState({ annexorgunit:newd });
        },
     onDownload: this.handledown,
     onRemove(infos){
      let uid=infos.uid;
      const id=_this.props.id;
      Uploads.removefile({sourcetype: "noticeorgunit",sourceid:id,uid:uid}).then(data => {
           if(data.code==="sucess"){
              notification.success(data.msg);
           }
           else{
            notification.error(data.msg);
            }
          }).catch(error => {
            notification.error(get(error, "response.data.message", "删除失败."));
          });
     },
      showUploadList: {
      showDownloadIcon: true,
      downloadIcon: '下载',
      showRemoveIcon: true,
      removeIcon: <DeleteOutlined onClick={e => console.log(e, 'custom removeIcon event')} />,
    },
  };
  return props;
};
  render() {
    if (this.state.loading) return null;
    return(
      <div>
      <Form layout="horizontal" {...{labelCol: { span: 4 }, wrapperCol: { span: 14 },} }>
      <Row>
         {/* <Col span={10}>
            <Form.Item label="公开">
            <Checkbox checked={this.state.is_public} onChange={e => this.setState({is_public:e.target.checked})}>编辑公开</Checkbox>
						</Form.Item>
				  </Col> */}
          <Col span={10}>
            <Form.Item label="部门">
              <Select style={{ width:  300 }}
                    showSearch
                    optionFilterProp="children"
                      value={this.state.orgunitid}
                      onChange={value => this.setState({orgunitid:value})}  
                      disabled ={! currentUser.isAdmin}>
              {(this.state.departmentdata || []).map(item => (
                <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
              ))}
              </Select>
						</Form.Item>
				  </Col>
        </Row>
      <Row>
         <Col span={10}>
            <Form.Item label="公共附件">
              <Upload {...this.getPdfURL()} fileList={this.state.annex} disabled={!currentUser.isAdmin}>
              {currentUser.isAdmin && ( <Button>
                  <UploadOutlined /> 上传
                </Button>)}
              </Upload>
						</Form.Item>
				  </Col>
          <Col span={10}>
            <Form.Item label="资料">
              <Upload {...this.getPdfURLorgunit()} fileList={this.state.annexorgunit}>
                <Button>
                  <UploadOutlined /> 上传
                </Button>
              </Upload>
						</Form.Item>
				  </Col>
        </Row>
      </Form>
      </div>
    );
  };
}
